<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <style>
    span {
      position: absolute;
      width: 100px;
      height: 100px;
      background-color: #000;
      display: block;
    }
  </style>
  <body>
    <button>按钮</button>
    <span></span>
  </body>

  <script>
    function animate(obj, target, callback) {
      clearInterval(obj.timer);

      obj.timer = setInterval(() => {
        let step = Math.ceil((target - obj.offsetLeft) / 10);
        step = step > 0 ? Math.ceil(step) : Math.floor(step);
        if (obj.offsetLeft === target) {
          clearInterval(obj.timer);
          callback && callback();
        }
        obj.style.left = obj.offsetLeft + step + "px";
      }, 15);
    }

    let button = document.querySelector("button");
    let span = document.querySelector("span");

    button.addEventListener("click", () => {
      animate(span, 500);
    });
  </script>
</html>
